/**
 * 
 */
package hu.gbalage.owlforms.impl;

import java.net.URI;
import java.util.HashSet;
import java.util.Set;

import org.semanticweb.owl.inference.OWLReasonerException;
import org.semanticweb.owl.model.OWLCardinalityRestriction;
import org.semanticweb.owl.model.OWLClass;
import org.semanticweb.owl.model.OWLProperty;

import hu.gbalage.owlforms.OWLFormsManager;
import hu.gbalage.owlforms.api.Field;
import hu.gbalage.owlforms.api.Form;
import hu.gbalage.owlforms.api.style.OWLFormsStyle;

/**
 * @author Grill Balazs (balage.g@gmail.com)
 *
 */
public class FormImpl implements Form {

	private final OWLClass baseclass;
	
	private Set<Field> fields = new HashSet<Field>();
	
	private final OWLFormsManager manager;
	
	protected Field getField(OWLProperty<?,?> property){
		URI uri = property.getURI();
		for(Field field : fields)
			if (field.getURI().equals(uri)) return field;
		
		Field result = null;
		try {
			result = new FieldImpl(manager,this,property);
			fields.add(result);
		} catch (OWLReasonerException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public FormImpl(OWLFormsManager manager, OWLClass baseclass){
		this.manager = manager;
		this.baseclass = baseclass;
		
		Set<OWLCardinalityRestriction<?,?>> crs = manager.getHelper().getProperties(baseclass); 
		
		for(OWLCardinalityRestriction<?,?> cr :crs){
			OWLProperty<?,?> property = (OWLProperty<?,?>)cr.getProperty();
			Field field = getField(property);
			FieldCardinalityFactory.setFieldCardinality((FieldImpl)field, cr);
		}
	}

	/* (non-Javadoc)
	 * @see hu.gbalage.owlforms.api.Form#listFields()
	 */
	public Set<Field> listFields() {
		return fields;
	}

	public URI getURI() {
		return baseclass.getURI();
	}
	
	public OWLFormsStyle getStyle() {
		return manager.getStyle();
	}
	
	public Field getField(URI field) {
		for(Field f : fields)
			if (f.getURI().equals(field)) return f;
		return null;
	}
	
}
